iT邦幫忙

2023 iThome 鐵人賽

DAY 15
0
Modern Web

React進階班,用typescript與jest製作自己的custom hooks庫系列 第 15

[Day 15] 今天換個方式測試useOutsideClick吧

  • 分享至 

  • xImage
  •  

我們來先做一個component,模擬這個情況吧

import * as React from 'react';
import { useOutsideClick } from '../../src';

function OutsideClickSample() {
  const [isOpen, setIsOpen] = React.useState(true);
  const handleOutsideClick = () => {
    setIsOpen(false);
  };
  const ref = useOutsideClick(handleOutsideClick);
  return (
    <section data-testid='outside'>
      <div data-testid='inside' ref={ref}>{isOpen ? "Open" : "Closed"}</div>
    </section>
  )
}

export default OutsideClickSample

接下來我們要模擬

  1. 點到section時應該要關掉
  2. 點擊div不應該關掉
import React from "react";
import OutsideClickSample from "../example/component/OutsideClickSample"; // 请更正为你的组件路径
import { render, act } from '@testing-library/react';

describe("useOutsideClick", () => {

  it('it should close when clicking outside', () => {
    const { getByTestId, getByText } = render(<OutsideClickSample />);
    const outSideSection = getByTestId("outside");

    expect(getByText('Open')).toBeTruthy();

    act(() => {
      outSideSection.click();
    });

    expect(getByText('Closed')).toBeTruthy();
  });

  it('it should not close when clicking inside', () => {
    const { getByTestId, getByText } = render(<OutsideClickSample />);
    const inSide = getByTestId("inside");

    expect(getByText('Open')).toBeTruthy();

    act(() => {
      inSide.click();
    });

    expect(getByText('Open')).toBeTruthy();
  });

})

首先用renderOutsideClickSample 模擬出來,使用兩個function,getByTestIdgetByText 他們一個可以取得有相同data-testid的dom,一個可以取得相同內容的dom,靠這兩個方法我們就能跟以前一樣測試了


上一篇
[Day 14] 常常使用的useOutsideClick
下一篇
[Day 16] 使用複製文字功能吧useCopyToClipboard
系列文
React進階班,用typescript與jest製作自己的custom hooks庫30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言